//下载参数
var http = require("http");
var https = require("https");
var fs = require("fs");
var path = require("path");

var dlInfo = {
    files : [],
};



/**
 * 删除文件夹下所有问价及将文件夹下所有文件清空
 * @param {*} path 
 */
 function emptyDir(path) {
    const files = fs.readdirSync(path);
    files.forEach(file => {
        const filePath = `${path}/${file}`;
        const stats = fs.statSync(filePath);
        if (stats.isDirectory()) {
            emptyDir(filePath);
        } else {
            fs.unlinkSync(filePath);
        }
    });
}
 
/**
 * 删除指定路径下的所有空文件夹
 * @param {*} path 
 */
function rmEmptyDir(path, level=0) {
    const files = fs.readdirSync(path);
    if (files.length > 0) {
        let tempFile = 0;
        files.forEach(file => {
            tempFile++;
            rmEmptyDir(`${path}/${file}`, 1);
        });
        if (tempFile === files.length && level !== 0) {
            fs.rmdirSync(path);
        }
    }
    else {
        level !==0 && fs.rmdirSync(path);
    }
}
 
/**
 * 清空指定路径下的所有文件及文件夹
 * @param {*} path 
 */
function clearDir(path) {
    emptyDir(path);
    rmEmptyDir(path);
}
 
/**
 * 下载回调
 */
function getHttpReqCallback (url, dirName, fileName) {

    var callback = function(res) {
        console.log("request: " + url + " return status: " + res.statusCode);
        var contentLength = parseInt(res.headers['content-length']);
        
        var downLength = 0;
    
        var out = fs.createWriteStream(dirName + "/" + fileName);
        res.on('data', function (chunk) {
            
            downLength += chunk.length;
            var progress =  Math.floor(downLength*100 / contentLength);
            var str = "dl progress ->"+ progress +"%";
            console.log(str);
            
            //写文件
            out.write(chunk, function () {
                //console.log(chunk.length);
                
            });
            
        });
        res.on('end', function() {
            console.log("end downloading " + url);
            if (isNaN(contentLength)) {
                console.log(url + " content length error");
                return;
            }
            if (downLength < contentLength) {
                console.log(url + " download error, try again");
                return;
            }
        });
    };

    return callback;
}

/**
 * 下载开始
 */
function startDownloadTask (url, dirName,fileName) {
    
    if (!fs.existsSync(dirName)) {
        fs.mkdirSync(dirName);
    }
    console.log("start downloading " + url);
    var req = null;
    if(url.indexOf("https")==0){
        req = https.request(url, getHttpReqCallback(url, dirName, fileName));
    }else{
        req = http.request(url, getHttpReqCallback(url, dirName, fileName));
    }
    req.on('error', function(e){
        console.log("request " + url + " error, try again");
    });
    req.end();
}


function startDownLoadByHttpUrl(url,param){
    
    var referrer = param.referrer;
    if(referrer.indexOf(dlInfo.domain)==-1 && url.indexOf(dlInfo.domain)==-1){
        return;
    }
    //script  stylesheet  subFrame image mainFrame
    console.log(url)
    var filename = path.basename(url)
    var filepath = path.dirname(url)
    var filetype = param.resourceType;
    console.log(param.resourceType)
    if(["mainFrame","subFrame"].includes(filetype) && !path.extname(url)){
        filename = "index.html";
        filepath = url;
    }
    if(filename.indexOf("?")!=-1){
        filename = filename.substring(0,filename.indexOf("?"))
    }
    console.log(filepath)
    console.log(filename)
    var subpath = "";
    if(["mainFrame","subFrame"].includes(filetype)){
        subpath = "";
    }else if(["script"].includes(filetype)){
        subpath="/js"
    }else if(["stylesheet"].includes(filetype)){
        subpath="/css"
    }else if(["image"].includes(filetype)){
        subpath="/image"
    }else{
        subpath="/other"
    }
    if(!dlInfo.pathmap[url]){
        dlInfo.files.push({url: url, filename: filename, filepath: filepath , filetype : filetype, newpath : subpath})
        dlInfo.pathmap[url] = true;
    }else{
        return;
    }
    startDownloadTask(url,dlInfo.savePath+subpath,filename)
}

// startDownloadTask('http://mirrors.tuna.tsinghua.edu.cn/apache/tomcat/tomcat-8/v8.5.41/bin/apache-tomcat-8.5.41.tar.gz','D://1024Workspace//extension','apache-tomcat-8.5.41.tar.gz');

//startDownloadTask('下载地址','本地存储路径','文件名');

function dealFilesPath(){
    dlInfo.files.map(item=>{
        if(["mainFrame","subFrame","stylesheet"].includes(item.filetype)){
            dealFileLink(item)
        }
    })
}

function dealFileLink(fileitem){
    var wholepath = dlInfo.savePath+fileitem.newpath+"/"+fileitem.filename;
    fs.readFile(wholepath,"utf8",(err,data)=>{
        if(err){
        
        }else{
            var content = data;
            content = content.replace(/src=['"](.*?)['"]|url[('"]+(.*?)['")]+/g, function(matchstr,link,link1) {
                link = link || link1;
                console.log(matchstr +"  " + link);
                if(!link){
                    console.log(arguments)
                    return;
                }
                var filename = path.basename(link);
                if(filename.indexOf("?")!=-1){
                    filename = filename.substring(0,filename.indexOf("?"))
                }
                var curitem = dlInfo.files.find((file)=>{return file.filename == filename})
                if(curitem){
                    var targetpath = "."+curitem.newpath+"/"+curitem.filename;
                    if(fileitem.filetype=="stylesheet"){
                        targetpath = "."+targetpath;
                    }
                    return matchstr.replace(link,targetpath);
                }
                return matchstr;
            });
            fs.writeFile(wholepath, content, 'utf8', (err)=>{
            });
        }
    })
}

module.exports = {
    initDlInfo(savePath,url=""){
        var domain = "www.aaabbbccc.com";
        if(url.indexOf("://")!=-1){
            try{
                var tmp  = url.substring(url.indexOf("://")+3,url.indexOf("/",8))
                domain = tmp || domain;
            }catch(ex){

            }
        }
        dlInfo = {
            files : [],
            pathmap : {},
            savePath : savePath || "C:/Users/flyswatter/Desktop/test",
            domain : domain,
        }
        if (!fs.existsSync(dlInfo.savePath)) {
            fs.mkdirSync(dlInfo.savePath);
        }
    },
    getDlInfo(){
        return dlInfo;
    },
    startHttpDl: startDownLoadByHttpUrl,
    dealFilesPath(){
        dealFilesPath();
    },
    clearDir(){  //比较危险,先不用

    }
}